from django.contrib.auth.models import User
from django.core.management.base import BaseCommand 
from os.path import dirname, isfile, join
from os import listdir
import os
import time
from django.conf import settings
import re
from ability.models import Chapter, Course, UserProfile

# 导入腾讯对象存储工具
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client

region = 'ap-chengdu'
region1= 'ap-beijing'
secret_id = settings.TENCENTCLOUD_SECRET_ID
secret_key = settings.TENCENTCLOUD_SECRET_KEY
endpoint = 'cos.ap-beijing.myqcloud.com'
bucket = 'beijing-1306286147'

config = CosConfig(Region=region1, SecretId=secret_id, SecretKey=secret_key, Endpoint=endpoint)
# 2. 获取对象存储客户端对象
cos_client = CosS3Client(config)


'''
  [
    {
      name:  "course name",
      chapters: [{
        name: "chapter name",
        editor: "video",
        key: "/asdfasd"
      }]
    }
  ]
'''


class Command(BaseCommand):
  help = 'import student from oracle'

  def handle(self, *args, **options):
      print('handle import points')
      pointdir = "/mnt/NewHDD/" 
      onlyfiles = [f for f in listdir(pointdir) if not isfile(join(pointdir, f))]
      user = UserProfile.objects.filter(username="13800138000").first()
      teacher = user.teacher
      for f in onlyfiles:
        coursepath = pointdir + f
        course_name = re.sub('^[0-9\+]{1,3}', '', f)
        course = Course.objects.filter(course_name=course_name).first()
        if course is None:
          print("create course: {}".format(course_name))
          course = Course()
          course.course_name = course_name
          course.theo_hours = 60
          course.prac_hours = 60
          course.credit = 5
          course.describe = course_name
          course.status = 'N'
          course.course_type = 'E'
          course.save()
          course.teacher_set.add(teacher)
        files = [_f for _f in listdir(coursepath) if isfile(join(coursepath, _f)) and not _f.startswith('.')]
        for f1 in files:
          print(f1)
          if f1.endswith('pdf') or f1.endswith('mp4'):
              with open(join(coursepath, f1), 'rb') as fp:
                key = '/importcourse/' + str(course.id) + '/' + str(time.time()).replace('.', '') + '.' + f1.split('.')[-1]
                print('chapter key:{}'.format(key))
                response = cos_client.put_object(
                    Bucket=bucket,
                    Body=fp,
                    Key=key,
                    StorageClass='STANDARD',
                    EnableMD5=False
                )
                addr = response
                chapter = Chapter()
                chapter.course = course
                chapter.chapter_name = re.sub('^[0-9\+]{1,3}', '', f1)
                chapter.detail = key
                chapter.detail_type = 'P' if f1.endswith("pdf") else 'V'
                chapter.save()
                os.remove(join(coursepath, f1))
                print('remove file:{}', join(coursepath, f1))


